package com.mzm.service.util;

import java.util.ArrayList;
import java.util.List;

import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import com.mzm.api.CategoryDto;

/**
 * 
 * @author Daniel Orr
 * 
 */
public class CategoryDtoTreeModel implements TreeModel {

	private CategoryDto rootDto;
	private boolean showIds;

	NodeWrapper root = null;

	public CategoryDtoTreeModel(CategoryDto rootDto) {
		this.rootDto = rootDto;
	}

	public void reset() {
		rootDto = null;
		root = null;
	}

	public boolean isShowIds() {
		return showIds;
	}

	public void setShowIds(boolean showIds) {
		this.showIds = showIds;
	}

	@Override
	public Object getChild(Object parent, int index) {
		NodeWrapper nw = (NodeWrapper) parent;
		return nw.getChild(index);
	}

	@Override
	public int getChildCount(Object parent) {
		NodeWrapper nw = (NodeWrapper) parent;
		return nw.getChildCount();
	}

	@Override
	public int getIndexOfChild(Object parent, Object child) {
		NodeWrapper nw = (NodeWrapper) parent;
		return nw.getIndexOfChild(child);
	}

	@Override
	public Object getRoot() {
		if (root == null) {
			root = new NodeWrapper(rootDto);
		}
		return root;
	}

	@Override
	public boolean isLeaf(Object node) {
		NodeWrapper nw = (NodeWrapper) node;
		return nw.getChildCount() == 0;
	}

	@Override
	public void removeTreeModelListener(TreeModelListener l) {
	}

	@Override
	public void valueForPathChanged(TreePath path, Object newValue) {
	}

	@Override
	public void addTreeModelListener(TreeModelListener l) {
	}

	private class NodeWrapper {
		CategoryDto n;
		List<NodeWrapper> children = null;

		public NodeWrapper(CategoryDto n) {
			this.n = n;
		}

		public NodeWrapper getChild(int index) {
			if (children == null) {
				initChildren();
			}
			if (index > children.size())
				return null;
			return children.get(index);
		}

		private void initChildren() {
			children = new ArrayList<NodeWrapper>();
			List<CategoryDto> cs = n.getChildren();
			if(cs == null)
				return;
			for (CategoryDto catDto : cs) {
				children.add(new NodeWrapper((CategoryDto) catDto));
			}
		}

		public int getIndexOfChild(Object child) {
			if (n instanceof CategoryDto) {
				CategoryDto cat = (CategoryDto) n;
				// cat = resultManagementFacade.getCategory(cat.getPath());
				List<CategoryDto> list = cat.getChildren();
				return list.indexOf(child);
			}
			return 0;
		}

		public int getChildCount() {
			if (!(n instanceof CategoryDto))
				return 0;
			if (children == null) {
				initChildren();
			}
			return children.size();
		}

		@Override
		public String toString() {
			String name = n.getName();
			String s = null;
			s = "".equals(name) ? "/" : name;
			if (showIds) {
				return s + " [" + n.getId() + "]";
			}
			return s;
		}
	}
}
